<!-- 操作日志 -->
<template>

  <div class="log-list">
    <!-- 过滤卡片 -->
    <el-card class="filter-card">
      <el-form :inline="true" :model="filterForm" class="demo-form-inline">
        <el-form-item label="操作人员ID">
          <el-input 
              v-model="filterForm.operatorId" 
              placeholder="请输入人员ID" 
              clearable></el-input>
        </el-form-item>
        <el-form-item label="部门名称">
          <el-select 
              v-model="filterForm.deptName" 
              placeholder="请选择部门" 
              clearable 
              style="width: 150px">
            <el-option label="技术部" value="1"></el-option>
            <el-option label="产品部" value="2"></el-option>
            <el-option label="运营部" value="3"></el-option>
            <el-option label="运维部" value="4"></el-option>
            <el-option label="销售部" value="5"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch" :loading="loading">
            <i class="el-icon-search"></i> 搜索
          </el-button>
          <el-button @click="resetFilter">
            <i class="el-icon-refresh"></i> 重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作日志列表卡片-->
    <el-card>
      <div slot="header" class="clearfix">
        <span>操作日志列表</span>
        <el-button 
            style="float: right; margin-top: -5px" 
            type="primary" 
            @click="handleAdd"
            >
            <i class="el-icon-plus"></i> 新增日志
          </el-button>
      </div>

      <!-- 操作日志表格 -->
      <el-table 
          :data="sysOperationLogList" 
          stripe 
          border 
          fit 
          highlight-current-row 
          v-loading="loading">
        <el-table-column prop="logId" label="编号" width="100"></el-table-column>
        <el-table-column prop="title" label="操作模块" width="120"></el-table-column>
        <el-table-column prop="requestMethod" label="请求方式"></el-table-column>
        <el-table-column prop="operatorId" label="操作人员ID"></el-table-column>
        <el-table-column prop="operatorName" label="操作人员"></el-table-column>
        <el-table-column prop="deptName" label="部门名称"></el-table-column>
        <el-table-column prop="operTime" label="操作时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.operTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="操作状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'danger' : 'success'">
              {{ row.status === 1 ? '异常' : '正常' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" align="center">
          <template #default="{ row }">
            <el-link type="primary" @click="handleView(row)">查看</el-link>
            <el-divider direction="vertical" />
            <el-link type="danger" @click="handleDelete(row)">删除</el-link>
            <el-divider direction="vertical" />
            <el-link type="success" @click="handleEdit(row)">编辑</el-link>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination 
      @size-change="handleSizeChange" 
      @current-change="handleCurrentChange" 
      :current-page="currentPage"
      :page-sizes="[5, 10, 20, 50]" 
      :page-size="pageSize" 
      layout="total, sizes, prev, pager, next, jumper"
      :total="total" 
      class="pagination-container"
      ></el-pagination>
    </el-card>

    <!-- 操作日志详情/编辑弹窗-->
    <el-dialog
        v-model="dialogVisible" 
        :title="dialogTitle" 
        width="600px"
        :close-on-click-modal="false"
        @closed="resetForm"
    >
      <el-form 
          ref="logDetailForm"
          :model="logDetail" 
          :rules="logDetailRules" 
          label-width="120px"
          >

          <!-- 日志详情 -->
        <el-form-item label="操作模块" prop="title">
          <el-input 
              v-model="logDetail.title" 
              :disabled="isViewMode" 
              placeholder="请输入操作模块"
         />
        </el-form-item>

        <el-form-item label="业务类型" prop="businessType">
          <el-input 
              v-model="logDetail.businessType" 
              :disabled="isViewMode" 
              placeholder="请输入业务类型"
         />
        </el-form-item>

        <el-form-item label="方法名称" prop="method">
          <el-input 
              v-model="logDetail.method" 
              :disabled="isViewMode" 
              placeholder="请输入方法名称"
          />
        </el-form-item>

        <el-form-item label="请求方式" prop="requestMethod">
          <el-select 
              v-model="logDetail.requestMethod" 
              placeholder="请选择请求方式" 
              clearable 
              style="width: 150px">
            <el-option label="GET" value="1"></el-option>
            <el-option label="POST" value="2"></el-option>
            <el-option label="PUT" value="3"></el-option>
            <el-option label="DELETE" value="4"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="操作类别" prop="operationType" v-if="!isViewMode">
          <el-radio-group v-model="logDetail.operationType" style="display: inline-block">
            <el-radio label="1">后台用户</el-radio>
            <el-radio label="0">其他</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="操作类别" v-else>
          <el-tag :type="logDetail.operationType === 1 ? 'primary' : 'success'">
            {{ logDetail.operationType === 1 ? '后台用户' : '其他' }}
          </el-tag>
        </el-form-item>

        <el-form-item label="操作人员ID" prop="operatorId">
          <el-input v-model="logDetail.operatorId":disabled="isViewMode" />
        </el-form-item>

        <el-form-item label="操作人员" prop="operatorName">
          <el-input v-model="logDetail.operatorName":disabled="isViewMode" />
        </el-form-item>

        <el-form-item label="部门名称" prop="deptName">
          <el-select v-model="logDetail.deptName" placeholder="请选择部门" clearable style="width:100%">
            <el-option label="技术部" value="1"></el-option>
            <el-option label="产品部" value="2"></el-option>
            <el-option label="运营部" value="3"></el-option>
            <el-option label="运维部" value="4"></el-option>
            <el-option label="销售部" value="5"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="请求URL" prop="operUrl">
          <el-input v-model="logDetail.operUrl" :disabled="isViewMode" placeholder="请输入请求URL" />
        </el-form-item>

        <el-form-item label="主机地址" prop="operIp">
          <el-input v-model="logDetail.operIp" :disabled="isViewMode" placeholder="请输入主机地址" />
        </el-form-item>

        <el-form-item label="操作地点" prop="operLocation">
          <el-input v-model="logDetail.operLocation" :disabled="isViewMode" placeholder="请输入操作地点" />
        </el-form-item>

        <el-form-item label="请求参数" prop="operParam">
          <el-input v-model="logDetail.operParam" :disabled="isViewMode" placeholder="请输入请求参数" />
        </el-form-item>

        <el-form-item label="返回参数" prop="jsonResult">
          <el-input v-model="logDetail.jsonResult" :disabled="isViewMode" placeholder="请输入返回参数" />
        </el-form-item>

        <el-form-item label="操作状态" prop="status" v-if="!isViewMode">
          <el-radio-group v-model="logDetail.status" style="display: inline-block">
            <el-radio label="1">异常</el-radio>
            <el-radio label="0">正常</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="操作状态" v-else>
          <el-tag :type="logDetail.status === 1 ? 'danger' : 'success'">
            {{ logDetail.status === 1 ? '异常' : '正常' }}
          </el-tag>
        </el-form-item>

        <el-form-item label="错误消息" prop="errorMsg">
          <el-input v-model="logDetail.errorMsg" :disabled="isViewMode" placeholder="请输入错误消息" />
        </el-form-item>

        <el-form-item label="操作时间" prop="operTime">
          <el-input v-model="logDetail.operTime":disabled="isViewMode" />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button 
            v-if="!isViewMode" 
            type="primary" 
            @click="saveLog" 
            :loading="saving">
          保存
        </el-button>
        <el-button @click="dialogVisible = false">
          {{ isViewMode ? '关闭' : '取消' }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import axios from '@/utils/request';
export default {
  name: 'SysOperationLogList',
  data() {
    // 新增操作日志表单验证规则logDetailRules
    const validateOperIp = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('请输入主机地址'))
      }
      const reg = /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/
      if (!reg.test(value)) {
        return callback(new Error('请输入正确的IP地址'))
      } else {
        callback();
      }

    };
    return {
      loading: true,
      saving: false,
      filterForm: {
        operatorId: '',
        deptName: '',
      },
      sysOperationLogList: [],
      currentPage: 1,
      pageSize: 5,
      total: 0,
      dialogVisible: false,
      isViewMode: false,
      logDetail: {
        id: '',
        title: '',
        businessType: '',
        method: '',
        requestMethod: '',
        operationType: 1,
        operatorId: '',
        operatorName: '',
        deptName: '',
        operUrl: '',
        operIp: '',
        operLocation: '',
        operParam: '',
        jsonResult: '',
        status: 0,
        errorMsg: '',
        operTime: ''
      },
      logDetailRules: {
        title: [
          { required: true, message: '请输入操作模块', trigger: 'blur' }
        ],
        operatorId: [
          { required: true, message: '请输入操作人员ID', trigger: 'blur' }
        ],
        operIp: [
          { required: true, message: '请输入主机地址', trigger: 'blur' },
          { validator: validateOperIp, trigger: ['blur', 'change'] }
        ],
      }
    }
  },
  computed: {
    // 根据当前模式（查看/编辑/新增）动态生成标题
    dialogTitle() {
      return this.isViewMode ? '查看日志详情' : this.logDetail.logId ? '编辑日志信息' : '新增日志';
    },
  },
  mounted() {
    this.getSysOperationLogList();
  },
  methods: {
    // 获取日志列表
    getSysOperationLogList() {
      this.loading = false;
      axios.get('/sysOperationLog/page',{
        params: {
          operatorId: this.filterForm.operatorId,
          deptName: this.filterForm.deptName,
          current: this.currentPage,
          size: this.pageSize,
        }
      }).then(response => {
        if (response.data.code === 200) {
          this.sysOperationLogList = response.data.data.records;
          this.total = response.data.data.total;
        } else {
          this.$message.error(response.data.message || '获取日志列表失败');
        }
      });
    },

    // 搜索日志
    handleSearch() {
      this.currentPage = 1;
      this.getSysOperationLogList();
    },

    // 重置过滤条件
    resetFilter() {
      this.filterForm = {
        operatorId: '',
        deptName: '',
      };
      this.currentPage = 1;
      this.getSysOperationLogList();
    },

    // 处理分页大小变化
    handleSizeChange(size) {
      this.pageSize = size;
      this.currentPage = 1;
      this.getSysOperationLogList();
    },

    // 处理当前页码变化
    handleCurrentChange(page) {
      this.currentPage = page;
      this.getSysOperationLogList();
    },

    // 格式化日期
    formatDate(dateStr) {
      if (!dateStr) return '';
      const date = new Date(dateStr);
      return date.toLocaleString();
    },

    // 格式化操作类别
    formatOperationType(OperationType) {
      return OperationType === 1 ? '后台用户' : '其他';
    },

    // 格式化状态
    formatStatus(status) {
      return status === 1 ? '异常' : '正常';
    },

    // 处理新增日志
    handleAdd() {
      this.$router.push('/sysOperationLogAdd');
    },

    // 查看日志详情
    handleView(row) {
      this.logDetail = { ...row };
      this.isViewMode = true;
      this.dialogVisible = true;
    },

    // 编辑日志
    handleEdit(row) {
      this.logDetail = { ...row };
      this.isViewMode = false;
      this.dialogVisible = true;
    },

    // 重置表单
    resetForm() {
      if (this.$refs.logDetailForm) {
        this.$refs.logDetailForm.resetFields();
      }
    },

    // 保存和新增日志
    async saveLog() {
      try{
        // 验证表单
        const valid = await this.$refs.logDetailForm.validate();
        if (!valid) return;

        this.saving = true;

          // 发送请求
          axios.post('/sysOperationLog/saveOrUpdate', this.logDetail)
            .then(response => {
              if (response.data.code === 200) {
                this.$message.success(this.logDetail.logId ? '日志修改成功' : '日志新增成功');
                this.dialogVisible = false;
                // 刷新用户列表
                this.getSysOperationLogList();
              } else {
                this.$message.error(response.data.message || '操作失败，请重试');
              }
            })
          }catch (error) {
              console.error('保存失败', error);
              const errorMsg = error.response?.data?.message || '保存失败';
              this.$message.error(errorMsg);
          } finally {
              this.saving = false;
          }
    },

    // 删除日志
    handleDelete(row) {
      this.$confirm('确认删除该日志吗？', '删除确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(resp => {
        try{
        axios.delete('/sysOperationLog/delete', {
          params: {
            logId: row.logId
          }
        }).then(response => {
          if (response.data.code === 200) {
            this.$message.success('删除成功');
            this.handleCurrentChange(this.currentPage);
          } else {
            this.$message.error(response.data.message || '删除失败');
          }
        })
        } catch (error) {
          console.error('删除失败',error);
          this.$message.error('删除失败,请检查网络连接');
        }
        }).catch(() => {
          this.$message.info('已取消删除');
        })
      },
  }
}
</script>

<style scoped>
/* 操作日志样式 */
.log-list {
  padding: 20px;
}

.filter-card {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.clearfix:after {
  content: "";
  display: table;
  clear: both;
}
</style>